<template>
  <view class="grades-page">
    <u-navbar placeholder
              leftIcon="arrow-left"
              :title="$t('pages_event_grades_grades_msg_5eadd0e7')"
              @leftClick="goBack" />
    
    <!-- 搜索区域 -->
    <view class="search-section">
      <view class="search-form">
        <!-- <view class="form-item">
          <text class="label">姓名</text>
          <input class="input" 
                 v-model="searchForm.name" 
                 :placeholder="$t('pages_event_grades_grades_msg_8093e392')" 
                 placeholder-class="placeholder" >
        </view> -->
        
        <view class="form-item">
          <text class="label">身份证号</text>
          <input class="input" 
                 v-model="searchForm.card" 
                 :placeholder="$t('pages_event_grades_grades_desc_408c789f')" 
                 placeholder-class="placeholder" >
        </view>
        
      </view>
      
      <button class="search-btn" 
              :class="{ 'searching': searching }"
              @click="onSearch">
        {{ searching ? '查询中...' : '查询成绩' }}
      </button>
    </view>
    
    <!-- 成绩结果 -->
    <view class="result-section" v-if="gradeResults.length > 0">
      <view class="result-header-info">
        <text class="result-count">共找到 {{ gradeResults.length }} 条记录</text>
      </view>
      
      <view class="result-card" v-for="(gradeResult, index) in gradeResults" :key="gradeResult.originalData.id">
        <view class="result-header">
          <text class="result-title">{{ gradeResult.eventName }}</text>
        </view>
        
        <view class="result-content">
          <view class="info-item">
            <text class="info-label">姓名:</text>
            <text class="info-value">{{ gradeResult.name }}</text>
          </view>
		  
          
         <!-- <view class="info-item">
            <text class="info-label">赛事名称:</text>
            <text class="info-value">{{ gradeResult.eventName }}</text>
          </view> -->
		  
		  <view class="info-item">
		    <text class="info-label">参赛编号:</text>
		    <text class="info-value grade-rank">
		      {{ gradeResult.originalData.num || '暂无编号' }}
		    </text>
		  </view>
          
          <view class="info-item">
            <text class="info-label">枪声成绩:</text>
            <text class="info-value grade-score">
              {{ gradeResult.gunTime || '暂无成绩' }}
            </text>
          </view>
		  
		  <view class="info-item">
		    <text class="info-label">净成绩:</text>
		    <text class="info-value grade-score">
		      {{ gradeResult.netTime || '暂无成绩' }}
		    </text>
		  </view>
          
          <!-- <view class="info-item">
            <text class="info-label">状态:</text>
            <text class="info-value grade-status" 
                  :class="getStatusClass(gradeResult.status)">
              {{ getStatusText(gradeResult.status) }}
            </text>
          </view> -->
          
         <!-- <view class="info-item" v-if="gradeResult.remark">
            <text class="info-label">备注:</text>
            <text class="info-value">{{ gradeResult.remark }}</text>
          </view> -->
          
          <view class="info-item">
            <text class="info-label">报名时间:</text>
            <text class="info-value">{{ formatDate(gradeResult.originalData.createDate) }}</text>
          </view>
          
          <view class="info-item">
            <text class="info-label">报名费用:</text>
            <text class="info-value money">¥{{ gradeResult.originalData.money }}</text>
          </view>
          
          <!-- 分享按钮 -->
          <view class="share-actions">
            <button class="share-btn" @click="generatePoster(gradeResult, index)" :loading="gradeResult.generating">
              <!-- <text class="share-icon">🎨</text> -->
              <text class="share-text">{{ gradeResult.generating ? '生成中...' : (gradeResult.posterUrl ? '查看证书' : '生成证书') }}</text>
            </button>
            <!-- <button class="share-btn share-btn-secondary" @click="sharePoster(gradeResult, index)" :disabled="!gradeResult.posterUrl">
              <text class="share-icon">📤</text>
              <text class="share-text">分享成绩</text>
            </button> -->
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="hasSearched && gradeResults.length === 0">
      <image class="empty-image" src="/static/images/empty-grade.png" mode="aspectFit" />
      <text class="empty-text">暂无成绩信息</text>
      <text class="empty-desc">请确认输入信息是否正确，或稍后重试</text>
    </view>
    
    <!-- 使用说明 -->
    <view class="help-section" v-if="!hasSearched">
      <view class="help-card">
        <view class="help-title">查询说明</view>
        <view class="help-content">
          <text class="help-item">1. 请准确输入参赛时的姓名和身份证号</text>
          <text class="help-item">2. 成绩通常在活动结束后3-5个工作日内公布</text>
          <text class="help-item">3. 查询结果包含报名信息、支付状态和完赛时间</text>
          <text class="help-item">4. 如有疑问请联系活动组织方</text>
        </view>
      </view>
    </view>
    
    <!-- 隐藏的海报生成器 -->
    <l-painter ref="poster" 
               :board="posterData" 
               :hidden="true"
               :is-canvas-to-temp-file-path="false"
               custom-style="position: fixed; left: 200%"
               @success="onPosterSuccess"
               @fail="onPosterFail" />
    
    <!-- 备用Canvas -->
    <canvas canvas-id="fallbackCanvas" 
            style="position: fixed; left: 200%; width: 375px; height: 667px;"
            width="375" 
            height="667" />
    
    <!-- 海报预览弹窗 - 完全重写 -->
    <view v-if="showPosterPreview" class="poster-modal" @click="closePosterPreview">
      <view class="modal-content" @click.stop>
        <!-- 顶部标题栏 -->
        <view class="modal-header">
          <text class="modal-title">马拉松成绩海报</text>
          <text class="modal-close" @click="closePosterPreview">×</text>
        </view>
        
        <!-- 海报内容区域 -->
        <view class="poster-content">
          <view class="poster-wrapper">
            <!-- 主海报图片 -->
            <image 
              v-if="previewPosterUrl"
              :src="previewPosterUrl" 
              mode="aspectFit" 
              class="main-poster"
              @load="onImageLoad"
              @error="onImageError"
              @click="previewImage" />
            
            <!-- 加载状态 -->
            <view v-else class="no-poster-content">
              <text>海报加载中...</text>
            </view>
          </view>
        </view>
        
        <!-- 底部按钮 -->
        <view class="modal-footer">
          <button class="modal-btn save" @click="saveCurrentPoster">保存相册</button>
          <button class="modal-btn share" @click="shareCurrentPoster">立即分享</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import { createPosterSchema } from '@/poster_config.js'

export default {
  name: 'Grades-Query',
  computed: {
    ...mapState({
      systemInfo: (state) => state.app.systemInfo,
    }),
  },
  data() {
    return {
      searchForm: {
        name: '',
        card: ''
      },
      gradeResults: [],
      searching: false,
      hasSearched: false,
      eventId: null,
      posterData: null,
      currentPosterIndex: -1,
      showPosterPreview: false,
      previewPosterUrl: '',
      currentPreviewIndex: -1
    }
  },
  onLoad(options) {
    this.eventId = options.eventId || null
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    // 查询成绩
    async onSearch() {
      // 验证输入
      // if (!this.searchForm.name.trim()) {
      //   uni.showToast({
      //     title: this.$t('pages_event_grades_grades_msg_8093e392'),
      //     icon: 'none'
      //   })
      //   return
      // }
      
      if (!this.searchForm.card.trim()) {
        uni.showToast({
          title: this.$t('pages_event_grades_grades_desc_408c789f'),
          icon: 'none'
        })
        return
      }
      
      // // 简单验证身份证号格式
      // if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(this.searchForm.card)) {
      //   uni.showToast({
      //     title: '身份证号格式不正确',
      //     icon: 'none'
      //   })
      //   return
      // }
      
      try {
        this.searching = true
        this.hasSearched = true
        
        // 构造查询参数
        const params = {
          pageNum: 1,
          pageSize: 20,
          // name: this.searchForm.name.trim(),
          card: this.searchForm.card.trim()
        }
        
        
        // 调用API查询成绩
        const result = await this.$api.event.queryScore(params)
        
        if (result && result.length > 0) {
          // 处理多条成绩记录
          this.gradeResults = result.map(scoreData => ({
            name: scoreData.userName || this.searchForm.name,
            eventName: scoreData.name || this.$t('pages_event_grades_grades_msg_39834b94'),
            score: scoreData.netTime || scoreData.gunTime || this.$t('pages_event_grades_grades_msg_7579c040'),
            rank: this.$t('pages_event_grades_grades_msg_7c2e449a'), // API未返回排名信息
            status: this.getEventStatus(scoreData),
            remark: this.getStatusRemark(scoreData),
            queryTime: new Date().toISOString(),
            // 海报相关状态
            generating: false,
            posterUrl: null,
            // 保留原始数据以备后用
            originalData: scoreData
          }))
          
          // uni.showToast({
          //   title: `查询成功，找到${result.length}条记录`,
          //   icon: 'success'
          // })
        } else {
          this.gradeResults = []
          uni.showToast({
            title: this.$t('pages_event_grades_grades_desc_7b2f55d5'),
            icon: 'none'
          })
        }
      } catch (error) {
        this.gradeResults = []
        uni.showToast({
          title: '查询失败，请重试',
          icon: 'none'
        })
      } finally {
        this.searching = false
      }
    },
    
    // 获取成绩等级样式
    getGradeClass(score) {
      if (!score) return ''
      const num = parseInt(score)
      if (num >= 90) return 'grade-excellent'
      if (num >= 80) return 'grade-good'
      if (num >= 70) return 'grade-fair'
      return 'grade-poor'
    },
    
    // 获取活动状态
    getEventStatus(scoreData) {
      if (scoreData.netTime || scoreData.gunTime) {
        return 1 // 已完成
      }
      if (scoreData.status === 0) {
        return 0 // 进行中/已报名
      }
      return -1 // 未开始
    },
    
    // 获取状态备注
    getStatusRemark(scoreData) {
      const payStatusMap = {
        0: this.$t('pages_event_grades_grades_msg_9246fe88'),
        1: this.$t('pages_event_grades_grades_msg_8d02a562')
      }
      const statusMap = {
        0: this.$t('pages_event_grades_grades_msg_4166d8ef'),
        1: this.$t('pages_event_grades_grades_msg_fad5222c')
      }
      return `${statusMap[scoreData.status] || this.$t('pages_album_album_msg_903b25f6')} | ${payStatusMap[scoreData.payStatus] || this.$t('pages_event_grades_grades_msg_2b6512ae')}`
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: this.$t('pages_event_grades_grades_msg_fad5222c'),
        0: this.$t('pages_event_grades_grades_msg_4166d8ef'),
        '-1': this.$t('pages_event_grades_grades_msg_dd4e55c3')
      }
      return statusMap[status] || this.$t('pages_album_album_msg_903b25f6')
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const classMap = {
        1: 'status-completed',
        0: 'status-ongoing',
        '-1': 'status-pending'
      }
      return classMap[status] || 'status-unknown'
    },
    
    // 格式化时间
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}`
    },
    
    // 生成成绩海报
    async generatePoster(gradeResult, index) {
      // 如果已经有海报，直接预览
      if (gradeResult.posterUrl) {
        this.previewPoster(gradeResult, index)
        return
      }
      
      try {
        this.$set(this.gradeResults[index], 'generating', true)
        this.currentPosterIndex = index
        
        // 创建海报JSON配置
        const posterConfig = createPosterSchema(gradeResult)
        console.log('生成的海报配置:', posterConfig)
        
        // 等待DOM更新
        await this.$nextTick()
        
        // 使用render方法主动渲染海报
        if (this.$refs.poster && typeof this.$refs.poster.render === 'function') {
          console.log('使用render方法渲染海报')
          await this.$refs.poster.render(posterConfig)
        } else {
          // 回退到board属性方式
          this.posterData = posterConfig
        }
        
        // 延迟时间确保lime-painter渲染完成
        setTimeout(() => {
          console.log('开始生成海报，当前poster组件:', this.$refs.poster)
          
          if (this.$refs.poster) {
            console.log('poster组件存在，开始调用生成方法')
            
            // 尝试多种可能的API方法
            try {
              // 方法1: canvasToTempFilePath (最常用)
              if (typeof this.$refs.poster.canvasToTempFilePath === 'function') {
                console.log('使用canvasToTempFilePath方法')
                this.$refs.poster.canvasToTempFilePath({
                  fileType: 'jpg',
                  quality: 0.8,
                  success: (res) => {
                    console.log('海报生成成功:', res)
                    this.$set(this.gradeResults[index], 'posterUrl', res.tempFilePath)
                    this.$set(this.gradeResults[index], 'generating', false)
                    this.$nextTick(() => {
                      this.previewPoster(this.gradeResults[index], index)
                    })
                  },
                  fail: (err) => {
                    console.log('海报生成失败:', err)
                    this.tryFallbackGeneration(gradeResult, index)
                  }
                })
              }
              // 方法2: canvasToTempFilePathSync
              else if (typeof this.$refs.poster.canvasToTempFilePathSync === 'function') {
                console.log('使用canvasToTempFilePathSync方法')
                this.$refs.poster.canvasToTempFilePathSync({
                  fileType: 'jpg',
                  pathType: 'url',
                  quality: 0.8,
                  success: (res) => {
                    console.log('海报生成成功:', res)
                    this.$set(this.gradeResults[index], 'posterUrl', res.tempFilePath)
                    this.$set(this.gradeResults[index], 'generating', false)
                    this.$nextTick(() => {
                      this.previewPoster(this.gradeResults[index], index)
                    })
                  },
                  fail: (err) => {
                    console.log('海报生成失败:', err)
                    this.tryFallbackGeneration(gradeResult, index)
                  }
                })
              }
              // 方法3: render方法
              else if (typeof this.$refs.poster.render === 'function') {
                console.log('使用render方法')
                this.$refs.poster.render().then((res) => {
                  console.log('海报生成成功:', res)
                  this.$set(this.gradeResults[index], 'posterUrl', res)
                  this.$set(this.gradeResults[index], 'generating', false)
                  this.$nextTick(() => {
                    this.previewPoster(this.gradeResults[index], index)
                  })
                }).catch((err) => {
                  console.log('海报生成失败:', err)
                  this.tryFallbackGeneration(gradeResult, index)
                })
              }
              // 方法4: 检查是否有其他可用方法
              else {
                console.log('poster组件可用方法:', Object.getOwnPropertyNames(this.$refs.poster))
                console.log('poster组件原型方法:', Object.getOwnPropertyNames(Object.getPrototypeOf(this.$refs.poster)))
                this.tryFallbackGeneration(gradeResult, index)
              }
            } catch (error) {
              console.log('调用海报生成方法出错:', error)
              this.tryFallbackGeneration(gradeResult, index)
            }
          } else {
            console.log('poster组件不存在，使用备用方案')
            this.tryFallbackGeneration(gradeResult, index)
          }
        }, 3000)
        
      } catch (error) {
        this.$set(this.gradeResults[index], 'generating', false)
        uni.showToast({
          title: this.$t('pages_event_grades_grades_msg_caf12c8b'),
          icon: 'none'
        })
      }
    },
    
    // 预览海报
    previewPoster(gradeResult, index) {
      if (!gradeResult.posterUrl) {
        uni.showToast({
          title: this.$t('pages_event_grades_grades_msg_96ebbbf9'),
          icon: 'none'
        })
        return
      }
      
      
      this.previewPosterUrl = gradeResult.posterUrl
      this.currentPreviewIndex = index
      this.showPosterPreview = true
      
      // 检查数据是否正确设置
      this.$nextTick(() => {
      })
    },
    
    // 图片加载成功
    onImageLoad(e) {
      
      // uni.showToast({
      //   title: `图片加载成功 ${e.detail?.width}x${e.detail?.height}`,
      //   icon: 'none'
      // })
    },
    
    // 图片加载失败
    onImageError(e) {
      
      uni.showToast({
        title: '图片加载失败: ' + (e.detail?.errMsg || this.$t('pages_event_grades_grades_msg_974e7484')),
        icon: 'none'
      })
    },
    
    // 第二个图片加载成功
    onImageLoad2(e) {
      
      uni.showToast({
        title: `第二个图片成功 ${e.detail?.width}x${e.detail?.height}`,
        icon: 'none'
      })
    },
    
    // 第二个图片加载失败
    onImageError2() {
      
      uni.showToast({
        title: this.$t('pages_event_grades_grades_desc_bde7d0b9'),
        icon: 'none'
      })
    },
    
    // 关闭海报预览
    closePosterPreview() {
      this.showPosterPreview = false
      this.previewPosterUrl = ''
      this.currentPreviewIndex = -1
    },
    
    // 预览大图
    previewImage() {
      if (this.previewPosterUrl) {
        uni.previewImage({
          urls: [this.previewPosterUrl],
          current: this.previewPosterUrl
        })
      }
    },
    
    // 保存当前预览的海报
    async saveCurrentPoster() {
      if (!this.previewPosterUrl) return
      
      try {
        await this.saveImageToAlbum(this.previewPosterUrl)
        uni.showToast({
          title: this.$t('pages_event_grades_grades_msg_c1a3175c'),
          icon: 'success'
        })
      } catch (error) {
        uni.showToast({
          title: this.$t('pages_event_grades_grades_msg_6de920b4'),
          icon: 'none'
        })
      }
    },
    
    // 分享当前预览的海报
    shareCurrentPoster() {
      if (!this.previewPosterUrl) return
      
      this.shareToFriends(this.previewPosterUrl)
    },
    
    // 分享海报
    async sharePoster(gradeResult) {
      if (!gradeResult.posterUrl) {
        uni.showToast({
          title: this.$t('pages_event_grades_grades_msg_96ebbbf9'),
          icon: 'none'
        })
        return
      }
      
      // 显示分享选项
      uni.showActionSheet({
        itemList: [this.$t('pages_event_grades_grades_msg_a3c86e6d'), this.$t('pages_event_grades_grades_msg_b7387f5f')],
        success: async (res) => {
          try {
            if (res.tapIndex === 0) {
              // 保存到相册
              await this.saveImageToAlbum(gradeResult.posterUrl)
              uni.showToast({
                title: this.$t('pages_event_grades_grades_msg_c1a3175c'),
                icon: 'success'
              })
            } else if (res.tapIndex === 1) {
              // 分享给朋友
              this.shareToFriends(gradeResult.posterUrl)
            }
          } catch (error) {
            uni.showToast({
              title: this.$t('pages_event_grades_grades_msg_e8e25af0'),
              icon: 'none'
            })
          }
        }
      })
    },
    
    // 保存图片到相册
    saveImageToAlbum(imagePath) {
      return new Promise((resolve, reject) => {
        uni.saveImageToPhotosAlbum({
          filePath: imagePath,
          success: () => {
            resolve()
          },
          fail: (error) => {
            if (error.errMsg.includes('auth deny')) {
              uni.showModal({
                title: this.$t('pages_category_category_text_02d9819d'),
                content: this.$t('pages_event_grades_grades_desc_573c9fca'),
                success: (res) => {
                  if (res.confirm) {
                    uni.openSetting()
                  }
                }
              })
            }
            reject(error)
          }
        })
      })
    },
    
    // 备用海报生成方案
    async tryFallbackGeneration(gradeResult, index) {
      
      try {
        // 创建一个简单的Canvas生成方案
        const ctx = uni.createCanvasContext('fallbackCanvas', this)
        
        // 设置画布大小
        const canvasWidth = 375
        const canvasHeight = 667
        
        // 绘制背景
        ctx.setFillStyle('#007aff')
        ctx.fillRect(0, 0, canvasWidth, canvasHeight)
        
        // 设置字体和颜色
        ctx.setFillStyle('#ffffff')
        ctx.setFontSize(20)
        ctx.setTextAlign('center')
        
        // 绘制标题
        ctx.fillText(this.$t('pages_event_grades_grades_desc_b69d90a1'), canvasWidth / 2, 80)
        
        // 绘制姓名
        ctx.setFontSize(16)
        ctx.fillText('姓名：' + (gradeResult.name || this.$t('pages_event_grades_grades_participant')), canvasWidth / 2, 120)
        
        // 绘制活动名称
        ctx.fillText('活动：' + (gradeResult.eventName || this.$t('pages_event_grades_grades_msg_80c79b4c')), canvasWidth / 2, 160)
        
        // 绘制成绩
        ctx.fillText('成绩：' + (gradeResult.originalData?.gunTime || this.$t('pages_event_grades_grades_msg_7579c040')), canvasWidth / 2, 200)
        
        // 绘制到画布
        ctx.draw(false, () => {
          setTimeout(() => {
            uni.canvasToTempFilePath({
              canvasId: 'fallbackCanvas',
              success: (res) => {
                let posterPath = res.tempFilePath
                
                this.$set(this.gradeResults[index], 'posterUrl', posterPath)
                this.$set(this.gradeResults[index], 'generating', false)
                
                // 延迟预览确保数据更新
                this.$nextTick(() => {
                  this.previewPoster(this.gradeResults[index], index)
                })
              },
              fail: () => {
                this.$set(this.gradeResults[index], 'generating', false)
                uni.showToast({
                  title: this.$t('pages_event_grades_grades_msg_22a5a01d'),
                  icon: 'none'
                })
              }
            }, this)
          }, 100)
        })
        
      } catch (error) {
        this.$set(this.gradeResults[index], 'generating', false)
        uni.showToast({
          title: this.$t('pages_event_grades_grades_msg_22a5a01d'),
          icon: 'none'
        })
      }
    },
    
    // 创建增强版成绩信息视图
    createEnhancedScoreInfoViews(gradeResult) {
      const scoreItems = [
        {
          icon: '🔥',
          label: this.$t('pages_event_grades_grades_msg_cbb95bd6'),
          value: gradeResult.originalData.gunTime || this.$t('pages_event_grades_grades_msg_7579c040'),
          isTime: true,
          color: '#ff6b6b'
        },
        {
          icon: '⚡',
          label: this.$t('pages_event_grades_grades_msg_c11f2f23'),
          value: gradeResult.originalData.netTime || this.$t('pages_event_grades_grades_msg_7579c040'),
          isTime: true,
          color: '#4ecdc4'
        }
      ]
      
      const infoItems = [
        {
          icon: '📅',
          label: this.$t('pages_event_grades_grades_msg_82fad912'),
          value: this.formatDate(gradeResult.originalData.createDate),
          color: '#45b7d1'
        },
        {
          icon: '💰',
          label: this.$t('pages_event_grades_grades_msg_fb303279'),
          value: `¥${gradeResult.originalData.money}`,
          color: '#f9ca24'
        }
      ]
      
      return [
        // 成绩展示区（重点突出）
        {
          type: 'view',
          css: {
            marginBottom: '40rpx'
          },
          views: scoreItems.map(item => ({
            type: 'view',
            css: {
              background: `linear-gradient(135deg, ${item.color}15, ${item.color}08)`,
              border: `2rpx solid ${item.color}30`,
              borderRadius: '24rpx',
              padding: '30rpx',
              marginBottom: '20rpx',
              position: 'relative',
              overflow: 'hidden'
            },
            views: [
              // 背景装饰
              {
                type: 'view',
                css: {
                  position: 'absolute',
                  top: '-20rpx',
                  right: '-20rpx',
                  width: '100rpx',
                  height: '100rpx',
                  background: `${item.color}10`,
                  borderRadius: '50%'
                }
              },
              // 内容
              {
                type: 'view',
                css: {
                  display: 'flex',
                  alignItems: 'center',
                  position: 'relative',
                  zIndex: 1
                },
                views: [
                  {
                    type: 'view',
                    css: {
                      width: '80rpx',
                      height: '80rpx',
                      background: item.color,
                      borderRadius: '50%',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      marginRight: '24rpx'
                    },
                    views: [
                      {
                        type: 'text',
                        text: item.icon,
                        css: {
                          fontSize: '36rpx'
                        }
                      }
                    ]
                  },
                  {
                    type: 'view',
                    css: {
                      flex: 1
                    },
                    views: [
                      {
                        type: 'text',
                        text: item.label,
                        css: {
                          fontSize: '28rpx',
                          color: '#666666',
                          marginBottom: '8rpx'
                        }
                      },
                      {
                        type: 'text',
                        text: item.value,
                        css: {
                          fontSize: '36rpx',
                                      color: item.color
                        }
                      }
                    ]
                  }
                ]
              }
            ]
          }))
        },
        // 其他信息展示
        {
          type: 'view',
          css: {
            display: 'flex',
            flexWrap: 'wrap',
            gap: '20rpx'
          },
          views: infoItems.map(item => ({
            type: 'view',
            css: {
              flex: '1',
              minWidth: '48%',
              background: '#f8f9fa',
              borderRadius: '20rpx',
              padding: '24rpx',
              textAlign: 'center'
            },
            views: [
              {
                type: 'view',
                css: {
                  width: '60rpx',
                  height: '60rpx',
                  background: item.color,
                  borderRadius: '50%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  margin: '0 auto 16rpx'
                },
                views: [
                  {
                    type: 'text',
                    text: item.icon,
                    css: {
                      fontSize: '28rpx'
                    }
                  }
                ]
              },
              {
                type: 'text',
                text: item.label,
                css: {
                  fontSize: '24rpx',
                  color: '#999999',
                  marginBottom: '8rpx'
                }
              },
              {
                type: 'text',
                text: item.value,
                css: {
                  fontSize: '28rpx',
                  fontWeight: '600',
                  color: '#333333'
                }
              }
            ]
          }))
        }
      ]
    },
    
    // 创建简化版成绩信息视图
    createSimpleScoreInfoViews(gradeResult) {
      const infoItems = [
        {
          icon: '🔥',
          label: this.$t('pages_event_grades_grades_msg_cbb95bd6'),
          value: gradeResult.originalData.gunTime || this.$t('pages_event_grades_grades_msg_7579c040')
        },
        {
          icon: '⚡',
          label: this.$t('pages_event_grades_grades_msg_c11f2f23'),
          value: gradeResult.originalData.netTime || this.$t('pages_event_grades_grades_msg_7579c040')
        },
        {
          icon: '📅',
          label: this.$t('pages_event_grades_grades_msg_82fad912'),
          value: this.formatDate(gradeResult.originalData.createDate)
        },
        {
          icon: '💰',
          label: this.$t('pages_event_grades_grades_msg_fb303279'),
          value: `¥${gradeResult.originalData.money}`
        }
      ]
      
      return infoItems.map(item => ({
        type: 'view',
        css: {
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '24rpx',
          padding: '20rpx',
          background: '#f8f9fa',
          borderRadius: '16rpx'
        },
        views: [
          {
            type: 'view',
            css: {
              display: 'flex',
              alignItems: 'center'
            },
            views: [
              {
                type: 'text',
                text: item.icon,
                css: {
                  fontSize: '32rpx',
                  marginRight: '12rpx'
                }
              },
              {
                type: 'text',
                text: item.label,
                css: {
                  fontSize: '28rpx',
                  color: '#666666',
                  fontWeight: '500'
                }
              }
            ]
          },
          {
            type: 'text',
            text: item.value,
            css: {
              fontSize: '28rpx',
              color: '#333333',
              fontWeight: 'bold'
            }
          }
        ]
      }))
    },
    
    // 创建成绩信息视图（保留原方法以防兼容性问题）
    createScoreInfoViews(gradeResult) {
      return this.createSimpleScoreInfoViews(gradeResult)
    },
    
    // 海报生成成功回调
    onPosterSuccess(imagePath) {
      if (this.currentPosterIndex >= 0) {
        this.$set(this.gradeResults[this.currentPosterIndex], 'posterUrl', imagePath)
        this.$set(this.gradeResults[this.currentPosterIndex], 'generating', false)
        uni.showToast({
          title: this.$t('pages_event_grades_grades_msg_dd4bd818'),
          icon: 'success'
        })
      }
    },
    
    // 海报生成失败回调
    onPosterFail() {
      if (this.currentPosterIndex >= 0) {
        this.$set(this.gradeResults[this.currentPosterIndex], 'generating', false)
        uni.showToast({
          title: '生成失败，请重试',
          icon: 'none'
        })
      }
    },
    
    // 分享给朋友
    shareToFriends(imagePath) {
      // #ifdef MP-WEIXIN
      uni.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
      // #endif
      
      // #ifdef APP-PLUS
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 2,
        imageUrl: imagePath,
        success: () => {
          uni.showToast({
            title: this.$t('pages_event_grades_grades_msg_51672ce8'),
            icon: 'success'
          })
        },
        fail: () => {
          uni.showToast({
            title: this.$t('pages_event_grades_grades_msg_e8e25af0'),
            icon: 'none'
          })
        }
      })
      // #endif
    }
  },
}
</script>

<style lang="scss" scoped>
.grades-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.search-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.04);
}

.search-form {
  margin-bottom: 40rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  width: 120rpx;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  flex-shrink: 0;
}

.input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  
  .placeholder {
    color: #999;
  }
}

.search-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #007aff, #005bb5);
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
  box-shadow: 0 8rpx 16rpx rgba(0, 122, 255, 0.3);
  
  &.searching {
    opacity: 0.7;
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.result-section {
  margin: 20rpx;
}

.result-header-info {
  background: #f8f9fa;
  padding: 20rpx 30rpx;
  border-radius: 16rpx 16rpx 0 0;
  margin-bottom: 20rpx;
}

.result-count {
  font-size: 28rpx;
  color: #007aff;
  font-weight: 600;
}

.result-card {
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.04);
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.result-header {
  background: linear-gradient(135deg, #007aff, #005bb5);
  padding: 30rpx;
  text-align: center;
}

.result-title {
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
}

.result-content {
  padding: 40rpx;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  width: 140rpx;
  font-size: 28rpx;
  color: #666;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.grade-score {
  font-size: 32rpx;
  font-weight: 600;
  
  &.grade-excellent {
    color: #52c41a;
  }
  
  &.grade-good {
    color: #1890ff;
  }
  
  &.grade-fair {
    color: #fa8c16;
  }
  
  &.grade-poor {
    color: #f5222d;
  }
}

.grade-rank {
  color: #722ed1;
  font-weight: 600;
}

.grade-status {
  padding: 6rpx 16rpx;
  border-radius: 16rpx;
  font-size: 24rpx;
  
  &.status-completed {
    background: #e8f5e8;
    color: #52c41a;
  }
  
  &.status-ongoing {
    background: #e6f7ff;
    color: #1890ff;
  }
  
  &.status-pending {
    background: #fff7e6;
    color: #fa8c16;
  }
}

.money {
  color: #f5222d;
  font-weight: 600;
  font-size: 30rpx;
}

.share-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 30rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.share-btn {
  flex: 1;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
  border-radius: 44rpx;
  border: none;
  font-size: 28rpx;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  box-shadow: 0 8rpx 20rpx rgba(102, 126, 234, 0.3);
  transition: all 0.2s ease;
  
  &.share-btn-secondary {
    background: linear-gradient(135deg, #52c41a, #389e0d);
    box-shadow: 0 8rpx 20rpx rgba(82, 196, 26, 0.3);
    
    &:disabled {
      background: #d9d9d9;
      color: #999;
      box-shadow: none;
    }
  }
  
  &:active {
    transform: scale(0.96);
  }
  
  &:disabled {
    opacity: 0.5;
    transform: none;
  }
}

.share-icon {
  font-size: 28rpx;
}

.share-text {
  font-size: 24rpx;
  font-weight: 500;
}

// 海报预览弹窗样式
.poster-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(0, 122, 255, 0.9), rgba(0, 91, 181, 0.9));
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60rpx 40rpx;
  backdrop-filter: blur(10rpx);
}

.preview-container {
  background: #fff;
  border-radius: 32rpx;
  width: 100%;
  max-width: 680rpx;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 32rpx 80rpx rgba(0, 0, 0, 0.3);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(60rpx);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.preview-header {
  background: linear-gradient(135deg, #007aff, #005bb5);
  padding: 40rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-content {
  flex: 1;
}

.preview-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #fff;
  margin-bottom: 8rpx;
}

.preview-subtitle {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.preview-close {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:active {
    background: rgba(255, 255, 255, 0.3);
  }
}

.close-icon {
  font-size: 32rpx;
  color: #fff;
  font-weight: bold;
}

.preview-content {
  flex: 1;
  padding: 60rpx 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f8faff, #f0f6ff);
  min-height: 400rpx;
}

.poster-frame {
  position: relative;
  border-radius: 24rpx;
  box-shadow: 0 24rpx 60rpx rgba(0, 122, 255, 0.2);
  background: #fff;
  width: 500rpx;
  height: 600rpx;
  margin: 0 auto;
  overflow: visible;
}

.preview-image-simple {
  width: 90%;
  max-width: 600rpx;
  height: auto;
  max-height: 80vh;
  display: block;
  margin: 0 auto;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.no-image-simple {
  width: 90%;
  height: 400rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  margin: 0 auto;
}

.no-image-simple text {
  font-size: 28rpx;
  color: #999;
  margin: 10rpx 0;
}

.poster-watermark {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  background: rgba(0, 0, 0, 0.6);
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  backdrop-filter: blur(10rpx);
  z-index: 10;
  pointer-events: none;
}

.watermark-text {
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.9);
}

.preview-actions {
  display: flex;
  gap: 24rpx;
  padding: 40rpx;
  background: #fff;
}

.preview-btn {
  flex: 1;
  height: 96rpx;
  border-radius: 48rpx;
  border: none;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  transition: all 0.2s ease;
  
  &.save-btn {
    background: linear-gradient(135deg, #52c41a, #389e0d);
    color: #fff;
  }
  
  &.share-btn-primary {
    background: linear-gradient(135deg, #ff4d4f, #cf1322);
    color: #fff;
  }
  
  &:active {
    transform: scale(0.96);
  }
}

.btn-icon {
  font-size: 32rpx;
}

.btn-text {
  font-size: 28rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  text-align: center;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  color: #666;
  font-weight: 500;
  margin-bottom: 12rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
  line-height: 1.5;
}

/* 新的海报弹窗样式 - 覆盖旧样式 */
.poster-modal {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  background: rgba(0, 0, 0, 0.75) !important;
  backdrop-filter: blur(8rpx) !important;
  z-index: 10000 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  animation: modalFadeIn 0.4s ease-out !important;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    backdrop-filter: blur(0rpx);
  }
  to {
    opacity: 1;
    backdrop-filter: blur(8rpx);
  }
}

.modal-content {
  background: #fff !important;
  border-radius: 24rpx !important;
  width: 90% !important;
  max-width: 600rpx !important;
  max-height: 90vh !important;
  display: flex !important;
  flex-direction: column !important;
  overflow: hidden !important;
  box-shadow: 0 30rpx 80rpx rgba(0,0,0,0.3), 
              0 10rpx 30rpx rgba(0,0,0,0.2) !important;
  animation: modalSlideUp 0.4s ease-out !important;
}

@keyframes modalSlideUp {
  from {
    opacity: 0;
    transform: translateY(100rpx) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 美化头部 */
.modal-header {
  display: flex !important;
  justify-content: space-between !important;
  align-items: center !important;
  padding: 30rpx 40rpx !important;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: #fff !important;
  position: relative !important;
  overflow: hidden !important;
}

.modal-header::before {
  content: '' !important;
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  height: 2rpx !important;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.6), transparent) !important;
}

.modal-title {
  font-size: 36rpx !important;
  font-weight: 700 !important;
  color: #fff !important;
  text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.2) !important;
}

.modal-close {
  font-size: 36rpx !important;
  color: #fff !important;
  width: 64rpx !important;
  height: 64rpx !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  border-radius: 50% !important;
  background: rgba(255, 255, 255, 0.15) !important;
  backdrop-filter: blur(10rpx) !important;
  border: 1rpx solid rgba(255, 255, 255, 0.2) !important;
  transition: all 0.3s ease !important;
}

.modal-close:active {
  background: rgba(255, 255, 255, 0.25) !important;
  transform: scale(0.95) !important;
}

/* 海报内容区域 - 固定尺寸 */
.poster-content {
  flex: 1 !important;
  padding: 30rpx !important;
  background: #f8f9fa !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  min-height: 600rpx !important;
}

.main-poster {
  width: 450rpx !important;
  height: 600rpx !important;
  border-radius: 12rpx !important;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1) !important;
  background: #fff !important;
  display: block !important;
  object-fit: contain !important;
}

.poster-wrapper {
  position: relative !important;
  width: 450rpx !important;
  height: 600rpx !important;
  background: #fff !important;
  border-radius: 12rpx !important;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1) !important;
  overflow: hidden !important;
}

.main-poster:active {
  transform: scale(0.99) !important;
  transition: transform 0.2s ease !important;
}

.no-poster-content {
  position: absolute !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  text-align: center !important;
  color: #666 !important;
  font-size: 28rpx !important;
}

.debug-simple {
  position: absolute !important;
  top: 10rpx !important;
  right: 10rpx !important;
  background: rgba(0, 0, 0, 0.6) !important;
  color: white !important;
  padding: 8rpx 12rpx !important;
  border-radius: 16rpx !important;
  font-size: 20rpx !important;
}

.debug-section {
  margin-top: 20rpx !important;
  padding: 20rpx !important;
  background: #fff !important;
  border-radius: 8rpx !important;
  border: 1px solid #ddd !important;
}

.debug-info {
  display: block !important;
  font-size: 24rpx !important;
  color: #333 !important;
  margin: 5rpx 0 !important;
  word-break: break-all !important;
  line-height: 1.4 !important;
}

.no-poster {
  padding: 40rpx !important;
  text-align: center !important;
  background: #f0f0f0 !important;
  border-radius: 8rpx !important;
}

.no-poster text {
  font-size: 28rpx !important;
  color: #666 !important;
}

/* 简洁的底部按钮 */
.modal-footer {
  display: flex !important;
  gap: 20rpx !important;
  padding: 30rpx !important;
  background: #fff !important;
  border-top: 1rpx solid #eee !important;
}

.modal-btn {
  flex: 1 !important;
  // height: 80rpx !important;
  border-radius: 40rpx !important;
  border: none !important;
  font-size: 28rpx !important;
  font-weight: 500 !important;
  transition: all 0.2s ease !important;
}

.modal-btn.save {
  background: #52c41a !important;
  color: #fff !important;
}

.modal-btn.save:active {
  background: #389e0d !important;
  transform: scale(0.98) !important;
}

.modal-btn.share {
  background: #1890ff !important;
  color: #fff !important;
}

.modal-btn.share:active {
  background: #096dd9 !important;
  transform: scale(0.98) !important;
}

.help-section {
  margin: 20rpx;
}

.help-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.04);
}

.help-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 24rpx;
  text-align: center;
}

.help-content {
  display: flex;
  flex-direction: column;
}

.help-item {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &:before {
    content: '•';
    color: #007aff;
    margin-right: 12rpx;
    font-weight: bold;
  }
}
</style>